<template>
 <div v-cloak>
     <div class="align-right">
              <el-form :inline="true" :model="listQuery">
                  <div class="pull-right">
                    <el-form-item>
                        <el-input
                            placeholder="请输入用户名"
                            clearable
                            v-model="listQuery.loginId">
                        </el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-input
                            placeholder="请输入姓名"
                            clearable
                            v-model="listQuery.name">
                        </el-input>
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" @click="handleSearch" icon="el-icon-search" >搜索</el-button>
                    </el-form-item>
                  </div>
                <div>
                  <el-button type="primary"  icon="plus" @click="handleAdd">添加</el-button>
                </div>
              </el-form>
      </div>
    <el-row>
  <el-col :span="5" style='margin-top:22px;'>
    <el-input
      placeholder="输入关键字进行过滤"
      v-model="filterText">
    </el-input>
    <el-tree
      class="filter-tree"
      :data="organizes"
      node-key="id"
      ref="organizes"
      highlight-current
      :props="defaultProps"
      :expand-on-click-node="false"
      :filter-node-method="filterNode"
      @node-click="getNodeData"
      default-expand-all
      >
    </el-tree>
  </el-col>
  <el-col :span="19">
        <el-table
            ref="user"
            :data="tableUser"
            row-key="id"
            border
            highlight-current-row
            style="width: 100%">
            <el-table-column align="center" label="序号" width ="80">
                <template slot-scope="scope">
                <span >{{ scope.$index+1 }}</span>
                </template>
            </el-table-column>
            <el-table-column align="center"  class-name="status-col" label="用户名" min-width="100">
                <template slot-scope="scope">
                <span>{{scope.row.loginId }}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" class-name="status-col" label="姓名" min-width="100">
                <template slot-scope="scope">
                <span>{{scope.row.name }}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" class-name="status-col" label="性别" width="80">
                <template slot-scope="scope">
                <span>{{scope.row.sex }}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" class-name="status-col" label="所属机构" min-width="100">
                <template slot-scope="scope">
                <span>{{scope.row.organizeName }}</span>
                </template>
            </el-table-column>
             <el-table-column align="center" class-name="status-col" label="角色" min-width="250">
                <template slot-scope="scope">
                <span>{{scope.row.roleNames?scope.row.roleNames:'--' }}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" class-name="status-col" label="邮箱" min-width="180">
                <template slot-scope="scope">
                <span>{{scope.row.email }}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" class-name="status-col" label="手机号" min-width="120">
                <template slot-scope="scope">
                <span>{{scope.row.phone }}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" class-name="status-col" label="用户状态" min-width="100">
                <template slot-scope="scope">
                 <span v-if="scope.row.enable" style="color:blue">
                  正常
                </span>
                <span v-else style="color:red">
                  禁用
                </span>
                </template>
            </el-table-column>
             <el-table-column
                fixed="right"
                align="center"
                min-width="180px"
                label="操作">
                <template slot-scope="scope">
                    <div>
                        <el-button type="text"  @click="handleEdit(scope)" :disabled="scope.row.id == 1">修改</el-button>
                        <el-button type="text"  @click="configPermission(scope)" :disabled="scope.row.id == 1">分配角色</el-button>
                        <el-button type="text" @click="handleDel(scope)" :disabled="scope.row.id == 1">删除</el-button>
                    </div>                
                </template>
            </el-table-column>
        </el-table>
        <el-col :span="24" class="pagination-warp" v-if="tableUser.length>0">
            <div class="text-center">
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="listQuery.currentPage"
                    :page-sizes="[5, 10, 15, 20]"
                    :page-size="listQuery.size"
                    layout="total, sizes, prev, pager, next ,jumper"
                    :total="total">
                </el-pagination>
            </div>
        </el-col>
  </el-col>
    </el-row>
<el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible"  :before-close="cancel" center width="30%">
    <el-form :model="form" :rules="rules" ref="form" label-width="100px">
         <el-form-item prop="loginId" label="用户名">
            <el-input v-model="form.loginId" :disabled="dialogStatus == 'update'"></el-input>
        </el-form-item>
        <el-form-item  label="重置密码" v-if="dialogStatus == 'update'">
            <el-radio-group v-model="resetPass">
                <el-radio-button label="1">是</el-radio-button>
                <el-radio-button label="0">否</el-radio-button>
            </el-radio-group>
        </el-form-item>
        <el-form-item prop="password" label="密码" v-if="dialogStatus == 'create' || resetPass == 1">
            
            <el-input v-model="form.password" type="password"></el-input>
        </el-form-item>  
         <el-form-item prop="rpassword" label="重复密码" v-if="dialogStatus == 'create' || resetPass == 1">
            <el-input v-model="form.rpassword" type="password" ></el-input>
        </el-form-item>  
        <el-form-item  label="姓名">
            <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item  label="性别">
            <el-radio-group v-model="form.sex" >
                <el-radio class="radio" border label="男">男</el-radio>
                <el-radio class="radio" border  label="女">女</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item prop="organizationId" label="所属机构">
             <menu-treeselect  
                :options="organizes"
                :normalizer="normalizer"
                :show-count="true"
                v-model="form.organizationId"
                placeholder="请选择所属机构">
            </menu-treeselect>
        </el-form-item>
        <el-form-item  label="邮箱">
            <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item  label="手机号">
            <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item prop="enable" label="状态">
            <el-radio-group v-model="form.enable" >
                <el-radio class="radio" border :label="1">正常</el-radio>
                <el-radio class="radio" border :label="0">禁用</el-radio>
            </el-radio-group>
        </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel()">取 消</el-button>
      <el-button v-if="dialogStatus=='create'" type="primary" @click="create('form')">确 定</el-button>
      <el-button v-else type="primary" @click="update('form')">确 定</el-button>
    </div>
  </el-dialog>
   <el-dialog title="角色分配" :visible="dialogRoleVisible" :before-close="rolecancel">
            <div> 
                <el-input v-model="config.id" v-show="false" ></el-input>
                <el-checkbox-group v-model="config.rolesId">
                    <el-checkbox v-for="role in roles" border :label="role.id" :key="role.id"  style="float:left;margin-left:5px">{{ role.name }}</el-checkbox>
                </el-checkbox-group>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogRoleVisible = false">取 消</el-button>
                <el-button type="primary" @click="submit()">确 定</el-button>
            </div>
   </el-dialog>
 </div>
</template>
<script>
import Treeselect from '@riophae/vue-treeselect'
  // import the styles
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { isPhone,isPassLenth} from '@/utils/validate';
import { getOrganizingTree } from '@/api/sys/organize'
import { getUserList,insert,update, deleteUser, configUserRoles } from '@/api/sys/user'
import {roleOfOrganization,roleOfUser} from '@/api/sys/role'
 export default {
  components: { 
    'menu-treeselect':Treeselect
  },
  data() {
    //电话验证
    const validatePhone = (rule, value, callback) => {
        if (value === null|| value === undefined || value === '') {
          callback(new Error('不能为空'));
        } else if(!isPhone(value)){
          callback(new Error('手机号码格式不正确'));
        } else {
          callback();
        }
    }
    //密码验证
    const validatePass = (rule, value, callback) => {
        if (value === null|| value === undefined || value === '') {
          callback(new Error('密码不能为空'));
        } else if(!isPassLenth(value)){
          callback(new Error('6-21字母和数字组成 '));
        } else {
          callback();
        }
    }
    //重复密码验证
    const validateRepass = (rule, value, callback) => {
        if (value === null|| value === undefined || value === '') {
          callback(new Error('重复密码不能为空'));
        } else if(this.form.password != value){
          callback(new Error('两次密码不一致 '));
        } else {
          callback();
        }
    }
    return {
        tableUser:[],
        total:null,
        organizes:[],
        resetPass: 0,
        roles: [],
        filterText: '',
        config:{
            id: undefined,
            rolesId:[]
        },
        dialogStatus:'',
        dialogFormVisible:false,
        dialogRoleVisible:false,
        textMap: {
            update: '编辑',
            create: '创建'
        },
        rules:{
            loginId: [
                { required: true, trigger: 'blur',message: "用户名不能为空" }
            ],
            name: [
                { required: true, trigger: 'blur',message: "姓名不能为空" }
            ],
            sex: [
                { required: true, trigger: 'change,blur',message: "必选项" }
            ],
            password:[
                { required: true, trigger: 'blur',validator: validatePass }
            ],
            rpassword:[
                { required: true, trigger: 'blur',validator: validateRepass }
            ],
            organizationId:[
                { required: true, trigger: 'change,blur',message: "必选项" }
            ],
            email: [
                { required: true, trigger: 'blur', message: "邮箱不能为空" },
                { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
            ],
            phone: [
                { required: true, trigger: 'blur', validator: validatePhone },
            ],
            enable: [
                 { required: true, trigger: 'change,blur',message: "必选项" }
            ]
           
        },
        defaultProps: {
            children: 'children',
            label: 'name'
        },
        form:{
          id:undefined,
          loginId:undefined,
          password:undefined,
          name: undefined,
          sex: undefined,
          phone:undefined,
          organizationId:undefined,
          email: undefined,
          enable:undefined
        },
        temp:{},
        listQuery:{
            currentPage: 1,
            size: 10,
            loginId: "",
            name: "",
            code:undefined
        }
    }
  },
  created() {
      this.getList()
      this.getOrganizations()
  },
  watch: {
    filterText(val) {
      this.$refs.organizes.filter(val);
    }
  },
  methods:{
    getList() {
        getUserList(this.listQuery).then((response) => {
            if(response.code === 0){
              this.tableUser = response.data.records
              this.total = response.data.total
            }
        })
    },
    getOrganizations(){
        getOrganizingTree().then(response => {
          if (response.code === 0) {
            this.organizes = response.data
          }
      })
    },
     filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
     normalizer(node) {
      return {
        id: node.code,
        label: node.name,
        children: node.children
      }
    },
    getNodeData(data) {
        this.listQuery.code = data.code
        this.getList()
    },
    handleSearch(){
        this.listQuery.currentPage = 1
        this.getList()
    },
    handleSizeChange(val) {
        this.listQuery.currentPage = 1
        this.listQuery.size = val
        this.getList()
    },
    handleCurrentChange(val) {
        this.listQuery.currentPage = val
        this.getList()
    },
    handleAdd(){
        this.dialogStatus = "create"
        this.dialogFormVisible = true
        this.resetForm()
    },
    handleEdit(scope){
        this.dialogStatus = 'update'
        this.dialogFormVisible = true 
        const row = scope.row
        this.form = JSON.parse(JSON.stringify(row)) 
        this.form.password = ""
        this.temp = JSON.parse(JSON.stringify(row)) 
    },
    configPermission(scope) {
        this.config.rolesId = []
        const row = scope.row
        const param = {"code": row.organizationId}
        
        roleOfOrganization(param).then((response) => {
            if(response.code === 0){ 
                this.roles = response.data  
            }
        })
        this.config.id = row.id
        const param1 = {"id": row.id}
        roleOfUser(param1).then((response) => {
            if(response.code === 0){ 
                this.config.rolesId = response.data  
            }
        })
        this.dialogRoleVisible = true   
    },
    create(formName){
       const set = this.$refs
       set[formName].validate(valid => {
          if(valid){
            insert(this.form).then((response) => {
                if(response.code === 0){
                    this.getList()
                    this.$message({
                        message: response.msg,
                        type: 'success'
                    })
                    this.cancel()
                }
            })
          }
       })
    },
    submit(){
        this.$confirm('此操作将重置用户角色, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                configUserRoles(this.config).then((response) => {
                    if(response.code === 0){
                        this.dialogRoleVisible = false
                        this.getList()
                        this.$message({
                            message: response.msg,
                            type: 'success'
                        })  
                    }
                }) 
            }).catch(() => {
                    
            })
        
    },
    update(formName){
       const set = this.$refs
       set[formName].validate(valid => {
          if(valid){
            this.form.rolesName = []
            if(this.form.password == '' || this.form.password == undefined){
                this.form.password = this.temp.password
            }
            update(this.form).then((response) => {
                if(response.code === 0){
                    this.getList()
                    this.$message({
                        message: response.msg,
                        type: 'success'
                    })
                    this.cancel()
                }
            })
          }
       })
    },
    handleDel(scope){
        const row = scope.row
        const data = JSON.parse(JSON.stringify(row)) 
        row.delFlag = 1
        this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                 data.rolesName = []
                 deleteUser(data).then((response) => {
                    if(response.code === 0){
                        this.getList()
                        this.$message({
                            message: response.msg,
                            type: 'success'
                        })
                    }
                })
            }).catch(() => {
                   
            })
       
    },
    cancel(){
       this.dialogStatus = ''
       this.dialogFormVisible = false 
       const set = this.$refs
       set['form'].clearValidate()
       this.resetForm()
       this.resetPass = 0
    },
    resetForm(){
        this.form = {
          id:undefined,
          loginId: undefined,
          name: undefined,
          sex: undefined,
          password:undefined,
          phone: undefined,
          organizationId:this.listQuery.code,
          email: undefined,
          enable:undefined
        }
    },
    rolecancel(){
        this.dialogRoleVisible = false
    }
  }
 }
</script>
<style rel="stylesheet/scss" lang="scss">
.table-user{
  margin: 10px
}
 .table-search{
  margin: 10px;
  div{
      width: 200px;
      float: left;
      margin-right: 6px;
  }
}
.el-tree-node__label{
    font-size: 16px!important;
}
</style>
